package cn.tedu.straw.portal.controller;


import cn.tedu.straw.portal.dto.PostAnswerDTO;
import cn.tedu.straw.portal.ex.ParamValidationException;
import cn.tedu.straw.portal.security.LoginUserInfo;
import cn.tedu.straw.portal.service.IAnswerService;
import cn.tedu.straw.portal.util.Result;
import cn.tedu.straw.portal.vo.AnswerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.ValidationException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2020-11-12
 */
@RestController
@RequestMapping("/portal/answers")
public class AnswerController {
    @Autowired
    private IAnswerService answerService;

    @RequestMapping("/post")
    public Result<Void> post(@Valid PostAnswerDTO postAnswerDTO,
                             @AuthenticationPrincipal LoginUserInfo loginUserInfo,
                             BindingResult bindingResult){
    if(bindingResult.hasErrors()){
      String errorMessage=  bindingResult.getFieldError().getDefaultMessage();
      throw new ParamValidationException(errorMessage);
    }
        Integer userId = loginUserInfo.getId();
        String userNickName = loginUserInfo.getNickName();
        answerService.post(postAnswerDTO, userId, userNickName);
        return Result.ok();
    }

    @GetMapping("")
    public Result<List<AnswerVO>> getAnswersList(Integer questionId){
        System.out.println("questionId = " + questionId);
        if(questionId==null||questionId<1){
            throw  new ParamValidationException("获取答案列表失败！缺少必要参数！");
        }
        List<AnswerVO> answerVOList= answerService.getAnswersList(questionId);
        return Result.ok(answerVOList);
    }


}
